//
//  SEGNeighbourhoodListViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/16.
//

#import "SEGNeighbourhoodListViewModel.h"

@implementation SEGNeighbourhoodListViewModel
#pragma mark - life cycle
- (instancetype)init {
    if (self = [super init]) {
        [self initData];
        [self seg_creatListDataCommand];
        [self seg_creatCanclePraiseCommand];
        [self seg_creatPraiseCommand];
        [self seg_creatAllQueryCommenCommand];
        [self seg_creatDeleteCommentCommand];
        [self seg_creatSaveQuizAnswerCommand];
        [self seg_creatcommentToChildCommentCommand];
        [self seg_creatDeleteActionWithNeihborhoodInfoModelCommand];
        self.cancelPraiseCommand.allowsConcurrentExecution = YES;
        self.praiseCommand.allowsConcurrentExecution = YES;
    }
    return self;
}

- (void)dealloc {
    
}

#pragma mark - init
- (void)initData {
    self.tencentAdRenderCount = 10; //拉取腾讯广告的总数量
}

#pragma mark - send request
- (void)seg_creatListDataCommand {
    @weakify(self);
    self.listDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            NSString *cityID = [SEGProfileManager sharedManager].profile.cityId;
            //    [SVProgressHUD show];
            //获取活动列表
            __weak typeof(self) weakSelf = self;
            [self.sharedNewManager requestNeighborhoodWithScopeId:self.scopeType
                                                            objId:self.objId
                                                           cityId:cityID
                                                          objType:self.objType
                                                           pageNo:[NSString stringWithFormat:@"%ld",(unsigned long)self.pageNo]
                                                        pageLimit:@"20"
                                                      communityId:self.communityId
                                                         moduleId:@"2"
                                                         finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                //        [SVProgressHUD dismiss];
                //添加刷新控件 步骤4：停止动画
                if (weakSelf.pageNo == 1) {
                    [subscriber sendNext:nil];
//                    [weakSelf.tableView stopAnimatingWindmill];
                    self.recommendIndex = 1;
                }
                if (isSuccessed) {
                    //清空第一条数据ID
                    weakSelf.objId = nil;
                    weakSelf.objType = nil;
                    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kNeighbourFirstItemInfoKey];
                    [subscriber sendCompleted];
                }else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
            
            return nil;
        }];
    }];
}

- (void)seg_creatCanclePraiseCommand {
    @weakify(self);
    self.cancelPraiseCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        RACTupleUnpack(SEGSharedNeihborhoodInfoModel *infoModel,NSString *objType) = input;
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.socialManager requestCancelPraiseByobjId:infoModel.objId
                                                   objType:objType
                                                  Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    [subscriber sendCompleted];
                } else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
            return nil;
        }];
    }];
}

- (void)seg_creatPraiseCommand {
    @weakify(self);
    self.praiseCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        RACTupleUnpack(SEGSharedNeihborhoodInfoModel *infoModel,SEGSharedCommonUserModel *userModel,NSString *objType) = input;
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            [self.socialManager requestPraiseAttentByObjId:infoModel.objId
                                                   ObjType:objType
                                           objPicUrlForMsg:infoModel.picture.count > 0 ? infoModel.picture[0] : nil
                                            objTitleForMsg:infoModel.content
                                            byReviewUserId:userModel.userId
                                               parentObjId:infoModel.objId
                                             parentObjType:objType
                                             operationType:infoModel.operationType
                                                  isParent:@"1"
                                                  Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    [subscriber sendCompleted];
                } else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
            
            return nil;
        }];
    }];
}

- (void)seg_creatAllQueryCommenCommand {
    @weakify(self);
    self.allQueryCommenCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(SEGSharedNeihborhoodModel *model) {
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            [self.sharedNewManager requestAllQueryCommentsWithObjId:model.model.objId objType:model.model.objType finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {

                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}

- (void)seg_creatDeleteCommentCommand {
    @weakify(self);
    self.deleteCommentCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        RACTupleUnpack(NSString *objId,SEGSharedNeihborhoodInfoModel *infoModel) = input;
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            [self.sharedNewManager requestDeleteCommentWithCommentId:objId objType:infoModel.objType finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    SEGSharedNeihborhoodModel *model = self.sharedNewManager.neighborhoodListArray[self.selectedIndexPath.section];
                    SEGSharedNeihborhoodInfoModel *infoModel = model.model;
                    [self.sharedNewManager requestAllQueryCommentsWithObjId:infoModel.objId objType:infoModel.objType finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                        //重置子评论列表
                        model.comment = self.sharedNewManager.childCommentsArray;
                        if (model.comment.count <= 3) {
                            model.more = @"2";
                        }
                        [subscriber sendCompleted];
                    }];
                } else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
            
            return nil;
        }];
    }];
}

- (void)seg_creatSaveQuizAnswerCommand {
    @weakify(self);
    self.saveQuizAnswerCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id input) {
        
        RACTupleUnpack(NSString *nickName) = input;
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            SEGSharedNeihborhoodModel *model = self.sharedNewManager.neighborhoodListArray[self.selectedIndexPath.section];
            SEGSharedNeihborhoodInfoModel *infoModel = model.model;
            SEGNeighbourhoodOperationType operationType = [infoModel.operationType integerValue];
            
            NSString *pic = @"";
            if (infoModel.picture && infoModel.picture.count > 0) {
                pic = infoModel.picture[0];
            }
            
            [subscriber sendNext:@(1)];
            [self.sharedNewManager requestSaveQuizAnswerByquizId:infoModel.objId
                                                     answContent:self.commentContent
                                                         creator:nickName
                                                      byReviewId:nil
                                                    byReviewNick:nil
                                                  byReviewUserId:model.user.userId
                                                   objSendUserId:model.user.userId
                                                 objPicUrlForMsg:pic
                                                  objTitleForMsg:infoModel.content
                                                        objeType:infoModel.objType
                                                     parentObjId:infoModel.objId
                                                   parentObjType:[infoModel.objType integerValue]
                                                   operationType:infoModel.operationType
                                                 sourceCommentId:nil
                                                        isParent:@"1"
                                                        Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
                
                RACTuple *tmp = RACTuplePack(@(isSuccessed),codeType,errorMessage);
                [subscriber sendNext:tmp];
                [subscriber sendCompleted];
            }];

            return nil;
        }];
    }];
}

- (void)seg_creatcommentToChildCommentCommand {
    @weakify(self);
    self.commentToChildCommentCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *nickName) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            SEGSharedNeihborhoodModel *model = self.sharedNewManager.neighborhoodListArray[self.selectedIndexPath.section];
            SEGSharedNeihborhoodInfoModel *infoModel = model.model;
            SEGSharedCommentChildCommentModel *commentModel = model.comment[self.selectChildIndex];
            SEGNeighbourhoodOperationType operationType = [infoModel.operationType integerValue];
            
            NSString *sourceCommentId;
            if (commentModel.comment.sourceCommentId && commentModel.comment.sourceCommentId.length > 0 && (![commentModel.comment.sourceCommentId isEqualToString:@"0"])) {
                sourceCommentId = commentModel.comment.sourceCommentId;
            }else {
                sourceCommentId = commentModel.comment.id;
            }
            
            [subscriber sendNext:@(1)];
            [self.sharedNewManager requestSaveQuizAnswerByquizId:infoModel.objId
                                                     answContent:self.commentContent
                                                         creator:nickName
                                                      byReviewId:commentModel.comment.id
                                                    byReviewNick:commentModel.user.nickName
                                                  byReviewUserId:commentModel.user.userId
                                                   objSendUserId:model.user.userId
                                                 objPicUrlForMsg:nil
                                                  objTitleForMsg:commentModel.comment.content
                                                        objeType:infoModel.objType
                                                     parentObjId:infoModel.objId
                                                   parentObjType:[infoModel.objType integerValue]
                                                   operationType:infoModel.operationType
                                                 sourceCommentId:sourceCommentId
                                                        isParent:@"2"
                                                        Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
                RACTuple *tmp = RACTuplePack(@(isSuccessed),codeType,errorMessage);
                [subscriber sendNext:tmp];
                [subscriber sendCompleted];
            }];
            
            return nil;
        }];
    }];
}

- (void)seg_creatDeleteActionWithNeihborhoodInfoModelCommand {
    @weakify(self);
    self.deleteActionWithNeihborhoodInfoModelCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(SEGSharedNeihborhoodInfoModel *infoModel) {

        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            __weak typeof(self) weakSelf = self;
            SEGNeighbourhoodOperationType type = [infoModel.operationType integerValue];
            if (type == SEGNeighbourhoodOperationType_Market) {//老接口
                [self.sHManager requestUpdateStatusBygoodsId:infoModel.objId
                                                     objType:infoModel.objType
                                                      status:[NSString stringWithFormat:@"%lu",(unsigned long)SEGEnumIdleStatus_Remove]
                                                    Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
                    if (!isSuccessed) {
                        [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                    }
                    [subscriber sendCompleted];
                }];
            }else {
                [weakSelf.sharedNewManager requestDeleteJoinHistoryWithObjId:infoModel.objId
                                                                     objType:infoModel.objType
                                                                    finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                    }
                    [subscriber sendCompleted];
                }];
            }
            
            
            return nil;
        }];
    }];
}



///请求发布视图列表
- (void)requestPublishList {
    [self.socialManager requestFindDictionaryInfoByCode:@"ugc_type" Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
    }];
}

#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods

#pragma mark - setter and getter

- (SEGSharedNewManager *)sharedNewManager {
    if (!_sharedNewManager) {
        _sharedNewManager = [[SEGSharedNewManager alloc] init];
    }
    return _sharedNewManager;
}
- (SEGHelpManager*)helpManager {
    if (!_helpManager) {
        _helpManager = [[SEGHelpManager alloc] init];
    }
    return _helpManager;
}
- (SEGSHManager*)sHManager {
    if (!_sHManager) {
        _sHManager = [[SEGSHManager alloc] init];
    }
    return _sHManager;
}
- (SEGCommunitySocialManager *)socialManager {
    if (!_socialManager) {
        _socialManager = [[SEGCommunitySocialManager alloc] init];
    }
    return _socialManager;
}

- (NSString *)scopeType {
    if (!_scopeType) {
        _scopeType = [NSString stringWithFormat:@"%lu",(unsigned long)SEGEnumScopeList_All];//默认显示全平台
    }
    return _scopeType;
}
- (NSString *)communityId {
    if (!_communityId) {
        _communityId = kAccountCommunityID;
    }
    return _communityId;
}

- (NSMutableDictionary *)cellHightDict {
    if (!_cellHightDict) {
        _cellHightDict = [NSMutableDictionary new];
    }
    return _cellHightDict;
}

- (void)setObjId:(NSString *)objId {
    _objId = ValueToString(objId);
}
@end
